﻿using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using QzEbook.Common;
using QzEbook.Common.Book;
using System.Text;
using System.Web;

/// <summary>
///BookInfo 的摘要说明
/// </summary>
/// 
namespace QzEbook.AccessObject
{
    public class Book : abstractAccess<Book> 
    {

        private int bookId;
        private int editorId;
        private int categoryId;

        private string title;
        private string content;
        private int hit;
        private int readers;
        private int favorites;

        private int comments;
        private int auditing;
        private int price;
        private bool isVisible;
        private List<Tag> oldTagList;
        private List<Tag> tagList;

        private bool viewType;
        private int width;
        private int height;
        private string thumb;

        private DateTime postDate;
        private double costbyte;

        private Bg bg;
        private BgSound bgSound;


        #region 属性
        public int BookId
        {
            get { return bookId; }
            set { bookId = value; }
        }       

        public int EditorId
        {
            get { return editorId; }
            set { editorId = value; }
        }
        public int CategoryId
        {
            get { return categoryId; }
            set { categoryId = value; }
        }
        public List<Tag> OldTagList
        {
            get { return oldTagList; }
            set { oldTagList = value; }
        }
        public List<Tag> TagList
        {
            get { return tagList; }
            set { tagList = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

        public string Content
        {
            get { return content; }
            set { content = value; }
        }
        public DateTime PostDate
        {
            get { return postDate; }
            set { postDate = value; }
        }
        public int Hit
        {
            get { return hit; }
            set { hit = value; }
        }
        public int Comments
        {
            get { return comments; }
            set { comments = value; }
        }
        public int Readers
        {
            get { return readers; }
            set { readers = value; }
        }
        public int Favorites
        {
            get { return favorites; }
            set { favorites = value; }
        }
        public int Price
        {
            get { return price; }
            set { price = value; }
        }
        public bool IsVisible
        {
            get { return isVisible; }
            set { isVisible = value; }
        }
        public int Auditing
        {
            get { return auditing; }
            set { auditing = value; }
        }

        public bool ViewType
        {
            get { return viewType; }
            set { viewType = value; }
        }
        public int Width
        {
            get { return width; }
            set { width = value; }
        }
        public int Height
        {
            get { return height; }
            set { height = value; }
        }
        public Bg Bg
        {
            get { return bg; }
            set { bg = value; }
        }

        public BgSound BgSound
        {
            get { return bgSound; }
            set { bgSound = value; }
        }

        public string Thumb
        {
            get
            {
                return thumb;
            }
            set { thumb = value; }
        }

        public string ThumbFullPath
        {
            get
            {
                return String.Format("{0}{1}", Config.UserBookSavePath, Thumb);
            }
        }

        public double Costbyte
        {
            get { return costbyte; }
            set { costbyte = value; }
        }
        #endregion

        public Book()
        {
            this.bgSound = new BgSound();
            this.bg = new Bg();
            this.oldTagList = new List<Tag>();
            this.tagList = new List<Tag>();
        }

        public Book bindThis(DataRow row)
        {
            return bindRow(row);
        }

        /// <summary>
        /// 绑定字段;
        /// </summary>
        /// <param name="row"></param>

        protected override Book bindRow(DataRow row)
        {
            Book book=new Book();
            book.BookId = int.Parse(row["BID"].ToString());
            book.EditorId = int.Parse(row["UID"].ToString());
            book.CategoryId = int.Parse(row["CID"].ToString());

            string tagStringList = row["BTag"].ToString();

            string patten = @"\{(?<ID>\d+)\}";
            Regex reg = new Regex(patten);

            Match m = reg.Match(tagStringList);
            book.oldTagList = new List<Tag>();
            while (m.Success)
            {
                Tag tag = new Tag();
                tag.Id = int.Parse(m.Groups["ID"].Value);
                tag.Name = Tag.getName(tag.Id);
                book.oldTagList.Add(tag);
                m = m.NextMatch();
            }

            book.Price = (Int32)row["BPrice"];
            book.Title = row["BTitle"].ToString();
            book.Content = row["BContent"].ToString();
            book.PostDate = (DateTime)row["BDate"];

            if (row.Table.Columns.Contains("BByte") && !string.IsNullOrEmpty(row["BByte"].ToString()))
            {
                book.Costbyte = (double)row["BByte"];
            }


            book.Hit = (Int32)row["BHit"];
            book.Readers = (Int32)row["BReaders"];
            book.Comments = (Int32)row["BComments"];
            book.Favorites = (Int32)row["BFavorites"];

            book.viewType = (bool)row["BViewType"];
            book.IsVisible = (bool)row["BIsVisible"];
            book.Auditing = (Int32)row["BAuditing"];
            book.Thumb = row["BThumb"].ToString();
            book.Width = (Int32)row["BWidth"];
            book.Height = (Int32)row["BHeight"];

            book.Bg.Path = row["BBackground"].ToString();
            book.Bg.Repeat = (bool)row["BBgrepeate"];
            book.Bg.Alpha = (Int32)row["BBgalpha"];

            book.BgSound.Path = row["BBgsound"].ToString();
            book.BgSound.Loop = (bool)row["BBgsoundloop"];
            return book;
        }

        /// <summary>
        /// 默认存储过程参数;
        /// </summary>
        /// <param name="command"></param>
        protected override void bindDefaultParameter(DbCommand command)
        {
            addParameter(command, "@BTitle", title);
            addParameter(command, "@CID", CategoryId);
            addParameter(command, "@BWidth", Width);
            addParameter(command, "@BHeight", Height);
            addParameter(command, "@BBgrepeate", Bg.Repeat);

            addParameter(command, "@BViewType", viewType);
            addParameter(command, "@BBgalpha", Bg.Alpha);
            addParameter(command, "@BBgsound", BgSound.Path);
            addParameter(command, "@BBgsoundloop", BgSound.Loop);
            addParameter(command, "@BContent", Content);

            addParameter(command, "@BIsVisible", IsVisible);
            addParameter(command, "@BAuditing", Auditing);
            addParameter(command, "@BPrice", Price);

            StringBuilder tagString = new StringBuilder();
            if (oldTagList != null)
            {
                foreach (Tag tag in oldTagList)
                {
                    tag.remove();
                }
            }
            foreach (Tag tag in TagList)
            {
                tag.insert();
                tagString.AppendFormat("{1}{0}{2}",tag.Id,"{","}");
            }
            if (HttpContext.Current.Cache["TagList"] != null)
            {
                HttpContext.Current.Cache.Remove("TagList");
            }
            addParameter(command, "@BTag", tagString.ToString());
        }

        /// <summary>
        /// 选取单本电子书;
        /// </summary>
        /// <returns></returns>
        protected override DataTable selectTable()
        {
            DbCommand command = CreateCommand("SelectBook");
            addParameter(command, "@BID", BookId);
            return DataAccess.ExcuteSelectCommand(command);
        }

        /// <summary>
        /// 按条件取出数据;
        /// </summary>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public List<Book> selectTopOrderBy(string where,string orderBy)
        {
            DbCommand command = CreateCommand("PaginationStore");
            addParameter(command, "@FdName", "BID");
            addParameter(command, "@SelectStr", "*");
            addParameter(command, "@WhereStr", where);
            addParameter(command, "@FromStr", "Qz_Book");
            addParameter(command, "@OrderByStr", orderBy);
            return bindTable(DataAccess.ExcuteSelectCommand(command));
        }

        /// <summary>
        /// 以用户名选取电子书;
        /// </summary>
        /// <param name="Uid"></param>
        /// <returns></returns>
        public DataTable selectUser(int Uid)
        {
            DbCommand command = CreateCommand("SelectUserBook");
            addParameter(command, "@UID", Uid);
            return DataAccess.ExcuteSelectCommand(command);
        }

        public DataTable selectAuditingBooks(int BAuditing)
        {
            DbCommand command = CreateCommand("SelectAuditingBook");
            addParameter(command, "@BAuditing", BAuditing);
            return DataAccess.ExcuteSelectCommand(command);
        }


        /// <summary>
        /// 重载插入电子书,并返回电子书id;
        /// </summary>
        /// <param name="bid">返回电子书索引</param>
        /// <returns></returns>
        public bool insert(ref int bid)
        {
            DbCommand command = CreateCommand("InsertBook");
            this.bindDefaultParameter(command);

            addParameter(command, "@UID", EditorId);
            addParameter(command, "@BID", BookId, ParameterDirection.Output);
   
            int i = -1;
            try
            {
                i = DataAccess.ExecuteNonQuery(command);
                bid = (int)command.Parameters["@BID"].Value;
            }
            catch
            {
            }
            return (i != -1);
        }

        /// <summary>
        /// 更新电子书
        /// </summary>
        /// <returns></returns>
        public override bool update()
        {
            DbCommand command = CreateCommand("UpdateBook");
            this.bindDefaultParameter(command);

            addParameter(command, "@BID", BookId);
            int i = -1;
            try
            {
                i = DataAccess.ExecuteNonQuery(command);
            }
            catch (Exception ex)
            {
                Utilities.LogError(ex);
                throw ex;
            }
            return (i != -1);
        }

        public string getTagListHTML()
        {
            StringBuilder sb = new StringBuilder();
            foreach (Tag tag in oldTagList)
            {
                sb.AppendFormat("   <a href=\"list.xhtml?Tid={0}\" title=\"{1}\">{1}</a>", tag.Id, tag.Name);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 删除电子书,提供用户id与电子书id
        /// </summary>
        /// <returns></returns>
        public override bool delete()
        {
            //先选择此书,取得它的所有TagID;
            this.select();

            DbCommand command = CreateCommand("DeleteBook");
            addParameter(command, "@BID", BookId);
            addParameter(command, "@UID", EditorId);

            int i = -1;
            try
            {
                i = DataAccess.ExecuteNonQuery(command);
                ///电子书删除成功的话,也要删掉Tag的引用数;
                if (i != -1)
                {
                    if (oldTagList != null)
                    {
                        foreach (Tag tag in oldTagList)
                        {
                            tag.remove();
                        }
                    }
                }
            }
            catch
            {
            }
            return (i > 0);
        }

        /// <summary>
        /// 是否要收费.
        /// </summary>
        /// <returns></returns>
        public bool isSale
        {
            get
            {
                if (this.Price == 0) return false;
                return true;
            }
        }

        public bool isSelf
        {
            get
            {
                return !this.isVisible;
            }
        }

        public string getAuditingHTML(string pad)
        {
            string html = string.Empty;
            string title=string.Empty;
            switch (this.Auditing)
            {
                case 0 :
                    break;
                case 1 :
                    html = "action1.gif";
                    title = "正在审核中...";
                    break;
                case 2 :
                    html = "action2.gif";
                    title = "审请被拒决";
                    break;
                case 3 :
                    html = "action3.gif";
                    title = "已通过审核";
                    break;
            }
            if (html == string.Empty)
            {
                return html;
            }
            return string.Format("<dfn><img src='{0}images/siteIcon/{1}' alt='{2}' /></dfn>",pad,html,title);

        }
    }
}
